package com.studyhub.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.studyhub.core.base.SecurityConstants;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;
import java.util.List;

/**
 * @author ：Baymax
 * @date ：Created in 2022/10/11 19:26
 * @description：将登录用户的JWT转化成用户信息的全局过滤器
 * @version:
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private com.studyhub.gateway.config.IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("AuthGlobalFilter处理路径: {}", path);
        
        // 检查是否为白名单路径，如果是则跳过JWT解析
        PathMatcher pathMatcher = new AntPathMatcher();
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, path)) {
                log.info("路径{}在白名单中，跳过JWT解析", path);
                return chain.filter(exchange);
            }
        }
        
        String token = exchange.getRequest().getHeaders().getFirst(SecurityConstants.JWT_TOKEN_HEADER);
        if(token==null){
            token=exchange.getRequest().getQueryParams().getFirst("token");
        }
        if (StrUtil.isEmpty(token)) {
            return chain.filter(exchange);
        }
        try {
            //从token中解析用户信息并设置到Header中去
            String realToken = token.replace(SecurityConstants.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            log.info("AuthGlobalFilter.filter() user:{}",userStr);
            
            // 将JWT中的字段映射到LoginUser对象的字段
            // JWT中的字段: user_name -> LoginUser中的username
            // JWT中的字段: client_id -> LoginUser中的clientId
            String mappedUserStr = userStr.replace("\"user_name\":", "\"username\":")
                                         .replace("\"client_id\":", "\"clientId\":");
            
            // 添加缺失的字段
            if (!mappedUserStr.contains("\"password\":")) {
                mappedUserStr = mappedUserStr.substring(0, mappedUserStr.length() - 1) + ",\"password\":null}";
            }
            if (!mappedUserStr.contains("\"enabled\":")) {
                mappedUserStr = mappedUserStr.substring(0, mappedUserStr.length() - 1) + ",\"enabled\":true}";
            }
            if (!mappedUserStr.contains("\"ip\":")) {
                mappedUserStr = mappedUserStr.substring(0, mappedUserStr.length() - 1) + ",\"ip\":null}";
            }
            if (!mappedUserStr.contains("\"roles\":")) {
                mappedUserStr = mappedUserStr.substring(0, mappedUserStr.length() - 1) + ",\"roles\":[]}";
            }
            
            log.info("AuthGlobalFilter.filter() mapped user:{}", mappedUserStr);
            ServerHttpRequest request = exchange.getRequest().mutate().header(SecurityConstants.USER_TOKEN_HEADER, mappedUserStr).build();
            exchange = exchange.mutate().request(request).build();
        }catch (ParseException e) {
            log.error("JWT解析异常: {}", e.getMessage());
            // 解析异常时继续执行，不中断请求流程
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
